iT邦幫忙

2025 iThome 鐵人賽

DAY 5
0
DevOps

連DevSecOps都不知道怎麼發音怎麼開始學習?系列 第 5

Day.5 世界線清理者: 使用Lint檢查程式碼及程式碼格式化

  • 分享至 

  • xImage
  •  

昨天我們學會了用快取加速世界線檢查,讓 CI 不用每次都重頭跑
但問題來了,即使測試過了,如果程式碼風格亂七八糟,長遠來說還是會出大事
所以今天,我們要請出「世界線清理者」:Lint(代碼靜態檢查工具)

什麼是Lint?

Lint = 程式碼的清道夫
它不會真的「執行」程式,而是像讀稿老師一樣,檢查你的程式碼有沒有

  • 拼字錯誤(Syntax錯誤,例如少一個 :)
  • 壞習慣(例如定義了變數卻沒用到)
  • 不符合規範(例如行太長,超過規定字元)
  • 潛在風險(像是隱藏的語法陷阱)

就像即使世界線還沒崩壞,D-mail發送錯誤訊號也會讓未來走歪
Lint 的存在,就是要幫我們「提前發現錯誤訊號

今天會使用flake8來示範如何偵測程式碼問題,因為它輕量、好上手
然後再用另一個叫black的工具自動整理

實作:把 Lint 加進 GitHub Actions

在 .github/workflows/ci.yml 裡新增一步「啟動世界線清理者」:

name: CI

on:
  push:
    branches: [ master ]
  pull_request:
    branches: [ master ]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: 下載世界線紀錄(程式碼)
        uses: actions/checkout@v3

      - name: 安裝 Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.10'

      - name: 安裝套件
        run: pip install -r requirements.txt

      - name: 安裝世界線清理者(flake8)
        run: pip install flake8

      - name: 啟動世界線檢查(測試)
        run: pytest -q

      - name: 啟動世界線清理者(Lint)
        run: flake8 .

然後 push 上去 → GitHub Actions 會在「Lint」那一步直接 Fail:

.\app.py:7:1: E305 expected 2 blank lines after class or function definition, found 1
.\app.py:8:23: W292 no newline at end of file
.\tests\test_worldline.py:1:1: E265 block comment should start with '# '
.\tests\test_worldline.py:10:1: E302 expected 2 blank lines, found 1
.\tests\test_worldline.py:13:1: E302 expected 2 blank lines, found 1
.\tests\test_worldline.py:14:38: W292 no newline at end of file

這些基本上都是不影響程式執行,但不符合PEP8規範的寫法
常見的像:

  1. E305 expected 2 blank lines after class or function definition, found 1
    函式或 class 定義結束後,要空兩行,但只空了一行
  2. W292 no newline at end of file
    檔案最後要有一個換行符號(\n)
  3. E265 block comment should start with '# '
    註解要有空格
  4. E302 expected 2 blank lines, found 1
    函式定義前要有兩行空白

而這些都可以透過接下來要介紹的這個工具來自動修正-black
在此之前先把這些套件都安裝起來
修改專案裡的requirements.txt

pytest
flake8
black

如果看預設規範不順眼,可以建立個設定檔./.flake8

# ./.flake8
[flake8]
max-line-length = 100 #限制該行最大字數
extend-ignore =
    E203,
    W503
exclude =
    .git,
    __pycache__,
    .venv,
    venv,
    dist,
    build
    

但一般不會交給CI更動我們的程式碼,所以我們在本地執行
先安裝最新套件,然後執行black

pip install -r requirements.txt
black .

之後再push到世界線檢查機構一次,會發現順利通過了
這就像岡部倫太郎每次「世界線跳躍」都要修正關鍵事件,不然未來就會爆炸


上一篇
Day.4 世界線穩定化:零件清單(套件管理)與快取機制
下一篇
Day.6 世界線審判庭:Pull Request Flow 與守門人
系列文
連DevSecOps都不知道怎麼發音怎麼開始學習?22
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言